package threading;

import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    //绝对时间戳，即当前时刻和基准时刻的ms数之差。基准时间即1970年1月1日00：00：00
    public long time;

    public MyTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }


    @Override
    public int compareTo(MyTask o) {
        //因为实现的是优先级队列，所以得实现比较规则，判断优先级
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    //定义一个锁对象
    private Object locker = new Object();
    public void schedule(Runnable runnable,long delay) {
        MyTask myTask = new MyTask(runnable,delay);
        queue.offer(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }
    public MyTimer() {
        Thread t = new Thread( () -> {
           while (true) {

               try {
                   synchronized (locker) {
                       MyTask myTask = queue.take();
                       long curTime = System.currentTimeMillis();
                       if (myTask.time <= curTime) {
                           myTask.runnable.run();

                       } else {
                           queue.put(myTask);
                          locker.wait(myTask.time - curTime);
                       }
                   }
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t.start();
    }

}
public class ThreadDemo24 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000);
        System.out.println("hello0");
    }
}
